
#include "util.h"

unsigned short CRC_16 (unsigned short CRC, unsigned short Cod)
{
	unsigned char i;

	CRC = CRC ^ (0x00FF & Cod);
	for (i = 0; i <= 7; i++)
	{
		if ((CRC & 0x0001) == 0x0001)
		{
			CRC = (CRC >> 1) ^ 0xA001;
		}
		else
		{
			CRC = CRC >> 1;
		}
	}

	return CRC;
}


void reverseWord(sWord * a) {
	unsigned char temp = a->Bytes.ByteHi;
	a->Bytes.ByteHi = a->Bytes.ByteLo;
	a->Bytes.ByteLo = temp;
}

unsigned short calculateMBcrc (mbPacket packet, int type)
{
	unsigned short tempCRC;


	tempCRC = 0xFFFF;
	
	tempCRC = CRC_16(tempCRC, packet.header.slaveAddress);
	tempCRC = CRC_16(tempCRC, packet.header.op);

	switch(type)
	{
	
		case(read_request): 
		{
			tempCRC = CRC_16(tempCRC,packet.tail.readPacketRequest.startWord.Bytes.ByteHi);
			tempCRC = CRC_16(tempCRC,packet.tail.readPacketRequest.startWord.Bytes.ByteLo);
			tempCRC = CRC_16(tempCRC,packet.tail.readPacketRequest.numWord.Bytes.ByteHi);
			tempCRC = CRC_16(tempCRC,packet.tail.readPacketRequest.numWord.Bytes.ByteLo);

			break;
		}
	}


	sWord CRC;

	CRC.Word = tempCRC;

	reverseWord(&CRC);

	return CRC.Word;
}


unsigned char * serializeMBpacket(mbPacket packet, unsigned char * buffer)
{

	buffer[0] = packet.header.slaveAddress;
	buffer[1] = packet.header.op;
	buffer[2] = packet.tail.readPacketRequest.startWord.Bytes.ByteHi;
	buffer[3] = packet.tail.readPacketRequest.startWord.Bytes.ByteLo;
	buffer[4] = packet.tail.readPacketRequest.numWord.Bytes.ByteHi;
	buffer[5] = packet.tail.readPacketRequest.numWord.Bytes.ByteLo;
	buffer[6] = packet.tail.readPacketRequest.CRC.Bytes.ByteHi;
	buffer[7] = packet.tail.readPacketRequest.CRC.Bytes.ByteLo;

	return buffer;
}



mbPacket deserializeMBpacket(unsigned char * buffer)
{
	mbPacket packet;


	return packet;
}


int validateData(unsigned char * buffer)
{

	return 1;
}

int receiveData(unsigned char * buffer, int len)
{
	int i = 0;
	for(i=0;i<len;i++)
	{
		buffer[i] = uart_getc();
	}

	return i;
}

int expectedLenght(mbPacket packet,int type)
{
	
	int lenghtCount = 2; // 2 bytes always for header

	switch(type)
	{
	
		case read_request:
		{
			
			lenghtCount = 6; // 2 bytes header + 2 bytes starting register field + 2 bytes CRC

			lenghtCount = lenghtCount + packet.tail.readPacketRequest.numWord.Word * 2; // expected data number of words by 2 (2 bytes per word)
			break;
		}
	}

	return lenghtCount;
}



